package smashedapples.utils
{
	import flash.display.DisplayObject;
	import flash.display.InteractiveObject;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import mx.core.IUIComponent;
	import mx.events.FlexMouseEvent;
	
	public class MouseUtils
	{
		
		public static function addMouseDownOutsideListener(o:DisplayObject):void
		{	
			var p : Proxy = new Proxy(o);
			
			p._mouseDownOutsideHandler = MouseUtils.mouseDownOutsideHandler;
			(p.owner as IUIComponent).systemManager.addEventListener(MouseEvent.MOUSE_DOWN, p.mouseDownOutsideHandler);
		} 
	
		private static function mouseDownOutsideHandler(owner:DisplayObject,event:MouseEvent):void
    	{	
    
        	if(owner.hitTestPoint(event.stageX, event.stageY, true)){}
        	else
			{
				if (owner is IUIComponent)
				if (IUIComponent(owner).owns(DisplayObject(event.target)))
					return; 

            	dispatchMouseDownOutsideEvent(owner,event);
			}
    	}
    	
    	
    	private static function dispatchMouseDownOutsideEvent(owner:DisplayObject, event:MouseEvent):void
	    {
	        const flexMouseEvent:MouseEvent = new FlexMouseEvent(FlexMouseEvent.MOUSE_DOWN_OUTSIDE);
	        const point:Point = owner.globalToLocal(new Point(event.stageX, event.stageY));
	        flexMouseEvent.localX = point.x;
	        flexMouseEvent.localY = point.y;
	        flexMouseEvent.buttonDown = event.buttonDown;
	        flexMouseEvent.shiftKey = event.shiftKey;
	        flexMouseEvent.altKey = event.altKey;
	        flexMouseEvent.ctrlKey = event.ctrlKey;
	        flexMouseEvent.delta = event.delta;
	        flexMouseEvent.relatedObject = InteractiveObject(event.target);
	        owner.dispatchEvent(flexMouseEvent);
	    }

	}
}


import flash.display.DisplayObject;
import flash.events.MouseEvent;
	
class Proxy
{
	public function Proxy(owner:DisplayObject):void
	{
		this.owner = owner;
	}
	
	
	public var owner : DisplayObject;
	public var _mouseDownOutsideHandler : Function;
	
	public function mouseDownOutsideHandler(event:MouseEvent):void
    {
        _mouseDownOutsideHandler(owner, event);
    }
}







